import { createI18n } from 'vue-i18n'
import zhCN from '@/locales/zh-CN'
import jaJP from '@/locales/ja-JP'
import enUS from '@/locales/en-US'

// 支持的语言列表
export const supportedLocales = [
  { code: 'zh-CN', name: '中文' },
  { code: 'ja-JP', name: '日本語' },
  { code: 'en-US', name: 'English' }
]

// 默认语言
const defaultLocale = 'zh-CN'

// 从本地存储获取用户设置的语言，如果没有则使用默认语言
const getStoredLocale = (): string => {
  try {
    const stored = localStorage.getItem('app-language')
    if (stored && supportedLocales.some(locale => locale.code === stored)) {
      return stored
    }
  } catch (error) {
    console.warn('Failed to get stored language:', error)
  }
  return defaultLocale
}

// 创建 i18n 实例
const i18n = createI18n({
  legacy: false, // 使用 Composition API 模式
  locale: getStoredLocale(),
  fallbackLocale: defaultLocale,
  messages: {
    'zh-CN': zhCN,
    'ja-JP': jaJP,
    'en-US': enUS
  }
})

// 设置语言
export const setLocale = (locale: string) => {
  if (supportedLocales.some(l => l.code === locale)) {
    i18n.global.locale.value = locale
    localStorage.setItem('app-language', locale)
    // 更新 HTML lang 属性
    document.documentElement.lang = locale
  }
}

// 获取当前语言
export const getCurrentLocale = () => {
  return i18n.global.locale.value
}

// 获取语言显示名称
export const getLocaleName = (locale: string) => {
  const found = supportedLocales.find(l => l.code === locale)
  return found ? found.name : locale
}

// 初始化 HTML lang 属性
document.documentElement.lang = getCurrentLocale()

export default i18n
